import 'package:flutter/material.dart';
import 'package:flutter_application/manager/db_manager.dart';
import 'package:flutter_application/pages/storage/novel_chapter_adapter.dart';
import 'package:flutter_application/pages/storage/novel_chapter_model.dart';
import 'package:hive/hive.dart';
import 'package:sqflite_sqlcipher/sqflite.dart';

class StoragePage extends StatefulWidget {
  const StoragePage({Key? key}) : super(key: key);

  @override
  State<StoragePage> createState() => _StoragePageState();
}

class _StoragePageState extends State<StoragePage> {
  String result = '';
  bool byHive = false;
  bool bySql = true;
  String userId = "user01";

  @override
  Widget build(BuildContext context) {
    return Scaffold(
        appBar: AppBar(
          title: const Text('数据存储'),
        ),
        body: Column(
          children: [
            Row(
              mainAxisAlignment: MainAxisAlignment.spaceEvenly,
              children: [
                ElevatedButton(onPressed: _initDB, child: const Text('初始化')),
                ElevatedButton(onPressed: _insert, child: const Text('添加')),
                ElevatedButton(onPressed: _delete, child: const Text('删除')),
                ElevatedButton(onPressed: _update, child: const Text('修改')),
                ElevatedButton(onPressed: _search, child: const Text('查找'))
              ],
            ),
            Text('运行结果：$result')
          ],
        ));
  }

  _timeDiff(block) async {
    var t1 = DateTime.now();

    await block();

    var t2 = DateTime.now();
    var difference = t2.difference(t1);
    _log('运行时间 - $difference');
  }

  _log(msg) {
    if (byHive) {
      msg = 'HIVE =》$msg\n';
    }
    if (bySql) {
      msg = 'SQL =》$msg\n';
    }
    print('$msg');
    setState(() {
      result += msg;
    });
  }

  _initDB() async {
    _timeDiff(() async {
      if (byHive) {
        var directory = await getDatabasesPath();
        var path = '$directory/caches/test.db';
        Hive
          ..init(path)
          ..registerAdapter(NovelChapterAdapter());
      }

      if (bySql) {
        DBManager.init(userId);
      }
    });
  }

  _insert() {
    _timeDiff(() async {
      //一共37本书  线上上架最多章节1017章  每章节在900-1900字都有
      int novelCount = 50;
      int chapterCount = 300;
      for (int i = 0; i < novelCount; i++) {
        if (byHive) {
          var box = await Hive.openBox('novel_$i');
          for (int j = 0; j < chapterCount; j++) {
            var chapter = NovelChapterModel();
            chapter.id = j;
            chapter.novelId = i;
            chapter.title = '章节标题$i';
            chapter.content = '章节内容$i' * 1000;

            var key = 'key_${chapter.novelId}_${chapter.id}';

            await box.put(key, chapter);
            await box.put(key, chapter.content);
          }
        }

        if (bySql) {
          for (int j = 0; j < chapterCount; j++) {
            var chapter = NovelChapterModel();
            chapter.id = j;
            chapter.novelId = i;
            chapter.title = '章节标题$i';
            chapter.content = '章节内容$i' * 1000;
            await DBManager.createChapterTable(chapter.novelId);
            await DBManager.insertChapter(chapter);
          }
        }
      }

      _log('添加完毕');
    });
  }

  _delete() async {
    _timeDiff(() async {
      if (byHive) {
        var box = await Hive.openBox('novel_49');
        var key = 'key_49_99';
        if (box.containsKey(key)) {
          box.delete(key);
          _log('删除成功');
        } else {
          _log('不存在');
        }
      }

      if (bySql) {
        var res = await DBManager.deleteChapter(39);
        _log('结果：$res');
      }
    });
  }

  _update() async {
    if (byHive) {
      var box = await Hive.openBox('tbl_novel_chapter');
      var key = 'key_100_99';
      if (box.containsKey(key)) {
        NovelChapterModel model = box.get(key);
        model.title = 'test sdfa ${model.title}';
        model.save();
        _log('更新完毕');
      } else {
        _log('不存在');
      }
    }

    if (bySql) {
      var res = await DBManager.updateChapter(1);
      _log('结果：$res');
    }
  }

  _search() async {
    if (byHive) {
      var box = await Hive.openBox('tbl_novel_chapter');
      var key = 'key_100_99';
      if (box.containsKey(key)) {
        _log('找到了 ${box.get(key).toString()}');
      } else {
        _log('没找到');
      }
    }

    if (bySql) {
      var res = await DBManager.searchChapter(38, 3);
      _log('结果：$res');
    }
  }
}

class NovelChapterDB {
  late Database database;

  //打开数据库
  Future open(String path) async {
    database = await openDatabase(
      path,
      version: 1,
      onCreate: (db, version) async {},
    );
  }

  //判断表是否存在
  isTableExits(String tableName) async {
    //内建表sqlite_master
    var sql =
        "SELECT * FROM sqlite_master WHERE TYPE = 'table' AND NAME = '$tableName'";
    var res = await database.rawQuery(sql);
    return res.isNotEmpty;
  }

  //插入数据
  insert(NovelChapterModel chapter) {}
}
